/**
 * @file Define the base controllern for all web controllers
 * 
 * @author Steve Gao<gaofu@parllay.com>
 */
var path = require('path');
var fs   = require('fs');


const BaseController    = require('../base-controller');
const Configuration     = require('../../constants').Configuration;

/**
 * The parent class for all web request controller
 * 
 * @class WebBaseController
 */
class WebBaseController extends BaseController {

    get name() {
        return 'WebBaseController';
    }

    get handlersPath() {
        return 'web-base';
    }

    get ControllerConfig() {
        return this.Application.getConfiguration(Configuration.WEB_CONTROLLER);
    }

    /**
     * Load web request handlers into controller
     */
    loadHandlers() {
        var me = this;
        let result = this._getHandlerFiles();

        if( result && result.handlerFiles) {
            result.handlerFiles.forEach((handleFile) => {
                if (path.extname(handleFile) === '.js') {
                    var realHanlderFile = path.resolve(result.path, handleFile);
                    var handlerName = `${me.handlersPath}:${path.basename(realHanlderFile, ".js")}`;
                    me.registerRequestHandler(handlerName, realHanlderFile);
                }
            });
        }
    }

    /**
     * Register request handler into web server
     * 
     * @name registerRequestHandler
     * @param {String} name - The handler name
     */
    registerRequestHandler(name, handlerFile) {
        this.Server.registerRequestHandler(this, name, handlerFile);
    }

    _getHandlerFiles() {
        var rootHandlerPath = path.resolve(
            this.Application.Context.getCurrentWorkDirectory(), 
            this.ControllerConfig.handlers_base_path
        );

        var controllerHandlersPath = path.resolve(rootHandlerPath, this.handlersPath);
        
        // Check if exists
        fs.accessSync(controllerHandlersPath);

        var files = fs.readdirSync(controllerHandlersPath);

        return {
            handlerFiles: files,
            path: controllerHandlersPath
        };
    }
}

module.exports = WebBaseController;